package com.aaa.member.controller;

import com.aaa.member.service.SendSms;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("sendtophone")
public class SmsApiController {
    @Autowired
    private SendSms sendSms;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone) {
        //调用发送方法，模拟真实业务，redis
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return phone + ":" + code + "已存在，还没有过期";
        }
        // 生成验证码并且存储到 redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);

        boolean isSend = sendSms.send(phone, "SMS_205459681", param);

        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 300, TimeUnit.SECONDS);
            return code;

        } else {
            return "发送失败！";
        }
    }
}
